<?php declare(strict_types=1);


namespace app\model;


class AuthGroup extends Base {

    protected $name = 'auth_group';

    // 设置字段信息
    protected $schema = [
        'group_id'     => 'int',
        'name'   =>'string',
        'description'  =>'text',
        'enabled'=>'tinyint',
        'create_at' => 'datetime',
        'update_at' => 'datetime',
        'delete_at' => 'datetime',
    ];

    // User Rights
    public function rights(){
        return $this->hasManyThrough('AuthRule','AuthGroupAccess','rule_id','group_id','rule_id');
    }

    public function access(){
        return $this->hasMany('AuthGroupAccess','group_id','group_id');
    }


    public function getAuthGroupList($page = 1,$pageSize = 15){
        $groups = $this->page($page,$pageSize)->select();
        return $groups;
    }

    public function getAuthGroupCount() : int {
        $count = $this->count();
        return $count;
    }

    public function getGroupByName(string $name): ?AuthGroup{
        $group = $this->where('name','=',$name)->find();
        return $group;
    }

    public function updateGroup(array $groupData): bool {
        $result = self::where('group_id','=',$groupData['group_id'])->save($groupData);
        return $result >=1 ? true : false;
    }

    public function createGroup(array $groupData): bool {
        $result = self::save($groupData);
        return $result >=1 ? true : false;
    }


    public function del(int $groupId) : bool {
        $group =  $this->where('group_id','=',$groupId)->find();
        if($group){
            $result = $group->delete();
            return $result >=1 ? true : false;
        }
        return false;
    }

    public function haveAuth(int $groupID) : array {
        $authList = AuthGroupAccess::where('group_id','=',$groupID)->column('rule_id');
        return $authList;
    }
}

 
